<template>
  <div class="page-container">
     <!--面包屑导航-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>活动中心</el-breadcrumb-item>
        <el-breadcrumb-item>其他类促销</el-breadcrumb-item>
        <el-breadcrumb-item>抽奖</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--工具栏-->
    <div class="toolbar" >
      <el-form :inline="true" :model="filters" :size="size" ref="filters" :rules="filtersRules">
        <el-row class="search-input">
          <el-form-item prop="activityName" label="活动名称：">
            <el-input clearable v-model="filters.activityName" placeholder="活动名称" maxlength="80"></el-input>
          </el-form-item>
          <el-form-item prop="promotionCode" label="活动ID：">
            <el-input clearable v-model="filters.promotionCode" placeholder="活动ID" maxlength="80"></el-input>
          </el-form-item>
          <el-form-item prop="lotteryTemplate" label="活动类型：">
            <el-select v-model="filters.lotteryTemplate" placeholder="全部" clearable>
              <el-option label="大转盘" value="1"></el-option>
              <el-option label="刮刮乐" value="2"></el-option>
              <el-option label="红包雨" value="3"></el-option>
              <el-option label="小we宝盒" value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="creatorNames" label="创建人：">
            <el-input clearable v-model="filters.creatorNames" placeholder="创建人" maxlength="80"></el-input>
          </el-form-item>
          <el-row class="times">
            <el-form-item prop="effStartTimeS" label="活动时间：" class="times">
              <el-date-picker
                v-model="filters.effStartTimeS"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="开始时间"
                class="input_postion w211"
                style="width:187px"
                clearable
                @change="changeStartDate"
                :picker-options="startDateDisabled"
              ></el-date-picker>
            </el-form-item>
             <span class="times-to">-</span>
            <el-form-item prop="effEndTimeE">
              <el-date-picker
                v-model="filters.effEndTimeE"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="结束时间"
                class="input_postion w211"
                style="width:187px"
                @change="changeEndDate"
                :picker-options="endDateDisabled"
              ></el-date-picker>
            </el-form-item>
          </el-row>
        </el-row>
        <!--操作按钮-->
        <el-row class="search-button">
          <el-form-item>
            <kt-button :label="$t('action.reset')" class="resetButton" icon="el-icon-refresh" :plain="true" type="primary" @click="resetForm('filters')" />
          </el-form-item>
          <el-form-item>
            <kt-button icon="el-icon-search" label="搜索" type="primary" @click="querySeach" class="searchButton"/>
          </el-form-item>
          <el-form-item>
            <kt-button label="创建活动" @click="createPage()"  type="primary" class="searchButton" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <div class="tab-container">
      <!-- tbs标签 -->
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane v-for="item in tabMapOptions" :key="item.key" :label="item.label" :name="item.key">
        </el-tab-pane>
      </el-tabs>
      <!-- jic table表格-->
      <div class="toolbar" >
        <!--表格显示列界面-->
        <table-column-filter-dialog
          ref="tableColumnFilterDialog"
          :columns="columns"
          @handleFilterColumns="handleFilterColumns"
        ></table-column-filter-dialog>
      </div>
      <!--表格内容栏-->
      <jic-table
        ref="JicTable"
        :data="pageResult"
        :operationWidth="390"
        :totalSize="totalSize"
        :columns="filterColumns"
        :showCopyDataOperation="true"
        :showCopyLinkOperation="false"
        :showDetailOperation="true"
        :showBatchDelete="false"
        :loading="loading"
        :btnList="btnList"
        @findPage="findPage"
        @handleDetail="handleDetail"
        @colseLottery="colseLottery"
        @handleCopyData="handleCopyData"
        @handleLinkData="handleLinkData"
				@submitReview="submitReview"
        @deleteLottery="deleteLottery"
        @updateLottery="updateLottery"
        @lotteryIntervene="lotteryIntervene"
				@review="review"
        ></jic-table>
    </div>

    <!-- 抽奖活动链接弹窗 -->
    <el-dialog class="el-dialog-style" title="抽奖链接" :visible.sync="dialogVisible"  :before-close="handleClose">
        <el-input clearable v-model="lotteryLink" style="width:70%" size="mini" disabled></el-input>
        <el-button class="tag-read" :data-clipboard-text="lotteryLink" @click="copyLink" size="mini" type="primary">复制</el-button>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="mini"  class="searchButton">关 闭</el-button>
        </span>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog class="el-dialog-style" title="审核" :visible.sync="dialogFormVisible">
      <el-form :model="verifyForm">
        <el-form-item>
          <el-input :rows="4" clearable v-model="verifyForm.checkRemark" autocomplete="off" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="reviewDialog(2)" size="mini" class="cancelButton">审核拒绝</el-button>
        <el-button type="primary" @click="reviewDialog(1)" size="mini" class="searchButton">审核通过</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import KtButton from "@/views/Core/KtButton";
import JicTable from "@/views/Core/LotteryTable";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { darkmagenta } from "color-name";
import tabPane from "./components/TabPaneLotteryRule";
import Clipboard from 'clipboard';
export default {
  name: "Tab",
  components: {
    tabPane,
    KtButton,
    JicTable,
    Clipboard,
    TableColumnFilterDialog
  },
  data() {
    return {
      filtersRules: {
        // activityName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // creatorNames: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },
      startDateDisabled: {},//开始时间限制
      endDateDisabled: {},//结束时间限制
      // 活动结束时间校验
      timeCheck: {
        disabledDate: time => {
          if (this.filters.effStartTimeS!=null && this.filters.effStartTimeS!='' && this.filters.effStartTimeS!= undefined) {
            return time.getTime() < new Date(this.filters.effStartTimeS) - 8.64e7
          }
        }
      },
      tableDataTotal:0,
      dialogVisible:false,
      dialogFormVisible:false,
      lotteryLink:'',//抽奖列表
      verifyForm:{},//审核弹窗form
  		formLabelWidth: '100px',
      tabMapOptions: [
        { label: "全部", key: '0' },
        { label: "进行中", key: '5' },
        { label: "已结束", key: '8' },
        { label: "已过期", key: '6' },
        { label: "已关闭", key: '7' },
        { label: "未开始", key: '3' },
        { label: "待提交", key: '1' },
        { label: "待审核", key: '2' },
        { label: "审核不通过", key: '4' },
        { label: "活动草稿", key: '9' }
      ],
      columns:[
        { prop: "promotionCode", label: "活动ID", minWidth: 290 },
        { prop: "activityName", label: "活动名称", minWidth: 200 },
        { prop: "lotteryTemplate", label: "抽奖形式", minWidth: 100 ,formatter:function(row, column, cellValue, index){
          if(row.lotteryTemplate ==1){
            return '大转盘';
          }else if(row.lotteryTemplate ==2){
            return '刮刮乐';
          }else if(row.lotteryTemplate ==3){
            return '红包雨';
          }else if(row.lotteryTemplate ==3){
            return '小we宝盒';
          }
        }},
        { prop: "effStartTime", label: "活动时间", minWidth: 360 ,formatter:function(row, column, cellValue, index){
          //活动开始结束时间拼接
          if(row.effStartTime !=null && row.effEndTime !=null ){
            return row.effStartTime + " - " + row.effEndTime;
          }
        }},
        { prop: "status", label: "活动状态", minWidth: 100 ,formatter:function(row, column, cellValue, index){
          //状态 1 待提交 2 待审核 3 审核不通过 4 进行中 5 已过期 6 已关闭 7 未开始 8 已结束 9 活动草稿
          if (row.status == "1") {
              return "待提交";
          } else if (row.status == "2") {
            return "待审核";
          } else if (row.status == "3") {
            return "未开始";
          } else if (row.status == "4") {
            return '审核不通过';
          } else if (row.status == "5") {
            return "进行中";
          } else if (row.status == "6") {
            return "已过期";
          } else if (row.status == "7") {
            return "已关闭";
          } else if (row.status == "8") {
            return "已结束";
          } else if (row.status == "9") {
            return "活动草稿";
          }
        }},
        { prop: "creatorName", label: "创建人", minWidth: 200 },
        { prop: "createTime", label: "创建时间", minWidth: 290 }
      ],
      //列表按钮
      btnList:[{
          "customLabel":"关闭",
          "isShowMethod":"3,5",
          "method":"colseLottery",
        },{
          "customLabel":"编辑",
          "isShowMethod":"1,4,9",
          "method":"updateLottery",
        },{
          "customLabel":"删除",
          "isShowMethod":"1,9",
          "method":"deleteLottery",
          "perms":"market:lottery:delete"
        }],
      pageResult: {},
      filterColumns: [],
      totalSize:0,
      pageRequest:{},
      loading:true,
      activeName: "0",
      size: "small",
      filters: {
        activityName:'',
        lotteryTemplate:'',
        creatorNames:'',
        effStartTimeS:'',
        effEndTimeE:'',
        status:'0',
        promotionCode:'',
      },
    };
  },
  methods: {
    querySeach(){
      this.pageRequest.pageNum =1 ;
      this.pageRequest.pageSize = 10;
      this.$refs.JicTable.restPage();
      this.findPage();
    },
    changeStartDate: function() {
      var this_ = this;
      this_.endDateDisabled = {
        disabledDate: time => {
          if (this_.filters.effStartTimeS) {
            return time.getTime() <= new Date(this_.filters.effStartTimeS).getTime();
          }
        }
      };
    },
    changeEndDate: function() {
      var this_ = this;
      this_.startDateDisabled = {
        disabledDate: time => {
          if (this_.filters.effEndTimeE) {
            return time.getTime() >= new Date(this_.filters.effEndTimeE).getTime();
          }
        }
      };
    },
    // 获取分页数据
    findPage: function(data) {
      //子组件传过来的分页参数 data.start 当前页 data.limit 当前页总条数
      this.loading = true;
      if(data != null && data.start != null){
        if(data.start != null){
          this.pageRequest.pageNum = data.start;
        }
        if(data.limit != null){
          this.pageRequest.pageSize = data.limit;
        }
      }
      let this_ = this;
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = this.pageRequest.pageNum;
      this_.filters.limit = this.pageRequest.pageSize;
      this.utils.request.queryLotteryThemeList(this_.filters, function (res) {
      this_.loading = false;
        if (res.data.rows.length < 1) {
          res.data.rows = [];
          res.data.total = 0;
        }
        this_.$refs.JicTable.findPage({content:res.data.rows,total:res.data.total});
      });
    },
    createPage() {
      // this.$router.push({path:"/LotteryRuleEvent/0"});
      this.$router.push({path:"/LotteryRuleEventCopy/0/1"});
    },
    //查看
    handleDetail: function(data) {
       
      this.$router.push({path:"/LotteryRuleInfo/" + data.row.id});
    },
    updateLottery: function(data) {
      // this.$router.push({path:"/LotteryRuleEvent/" + data.row.id});
      this.$router.push({path:"/LotteryRuleEventCopy/" + data.row.id + "/1"});
    },
    //复制抽奖活动
    handleCopyData: function(data) {
      this.$confirm("确定要复制该活动？", "提示", {
        type: "warning",
        closeOnClickModal: false,
      }).then(() => {
        if (data != null && data.row != null) {
          var params = {};
          params.id = data.row.id;
          var this_ = this;
          this.utils.request.copyLotteryActivity(params, function(res) {
            if (res.code == "0000") {
              this_.$message({message: "复制成功 ", type: "success"});
              this_.findPage(null);
            } else {
              this_.$message({ message: "操作失败, " + res.msg, type: "error" });
            }
          });
        }
      }).catch(() => {});
    },
    // 删除活动
    deleteLottery: function(data) {
      
      this.$confirm("确定要执行删除操作么？删除后不可恢复!", "提示", {
        type: "warning",
        closeOnClickModal: false,
      }).then(() => {
        if (data != null && data.row != null) {
          var params = {};
          params.id = data.row.id;
          var this_ = this;
          this.utils.request.deleteLotteryActivity(params, function(res) {
            if (res.code == "0000") {
              this_.$message({ message: "操作成功", type: "success" });
              this_.findPage(null);
            } else {
              this_.$message({ message: "操作失败, " + res.msg, type: "error" });
            }
          });
        }
      }).catch(() => {
      });
    },
    //关闭活动
    colseLottery: function(data) {
      let msg = ''
      if(data.row.status == 5){
        msg = '该活动正在进行中，确定要关闭它？关闭后不可再次开启。'
      }else{
        msg = '该活动即将进行，确定要关闭它？关闭后不可再次开启。'
      }
      let params = {};
      params.id = data.row.id;
      params.status = 7;//关闭状态为0
      var this_ = this;
      this.$confirm(msg, "提示", {
        type: "warning",
        closeOnClickModal: false,
      }).then(() => {
        this.utils.request.closeLotteryActivity(params, function(res) {
          if (res.code == "0000") {
            this_.$message({message: "活动已关闭 ", type: "success"});
            this_.findPage(null);
          } else {
            this_.$message({ message: "操作失败, " + res.msg, type: "error" });
          }
        });
      }).catch(() => {
      });
    },
    //抽奖干涉
    lotteryIntervene: function(data) {

    },
    //复制抽奖链接弹窗
    handleLinkData: function(data) {
      //测试复制 假链接
      this.lotteryLink = this.utils.imgUploadUrl;
      this.dialogVisible = true;
    },
    //关闭抽奖链接弹窗
    handleClose: function(data) {
      this.lotteryLink = '';
      this.dialogVisible = false;
    },
    //复制活动链接
    copyLink() {
      var clipboard = new Clipboard(".tag-read");
      clipboard.on("success", e => {
        this.$message({message: "复制成功,快去分享吧", type: "success"});
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on("error", e => {
        // 不支持复制
        this.$message({message: "该浏览器不支持自动复制 ", type: "error"});
        // 释放内存
        clipboard.destroy();
      });
    },
    //提交审核
    submitReview:function(data){
      let that = this;
      const loading = this.$loading({
        lock: true,
        text: '小的正在努力加载中......',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)'
      });
      this.utils.request.closeLotteryActivity({id:data.row.id,"status":2},res=>{
        loading.close();
        that.$message({ message: "提交审核成功", type: "success" });
        that.findPage();
      })
    },
    //审核
    review:function(data){
      this.dialogFormVisible =  true;
      this.verifyForm.id = data.row.id;
    },
    //审核
    reviewDialog:function(data){
      if(this.verifyForm.checkRemark==null||this.verifyForm.checkRemark==''){
        this.$message({ message: "审核意见不能为空", type: "error" });
        return false;
      }
      let that = this;
      this.verifyForm.verifyStatus = data;
      that.utils.request.verifyLotteryActivity(this.verifyForm,res=>{
        if(res.code == "0000"){
          that.dialogFormVisible =  false;
          that.$message({ message: "审核完成", type: "success" });
          that.findPage();
        }else{
          that.$message({ message: "审核失败", type: "error" });
        }
      })
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },
    //重置
    resetForm(formName) {

      //需要校验的keys
			// let keys = ["activityName","promotionCode","effEndTimeE","effStartTimeS","creatorNames"]
			// //调用校验
			// let  boo = this.seachTableUtils.checkFromIsNull(this.filters,keys)
			// if(!boo){
			// 	return;
      // }


      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
        this.pageRequest.pageNum =1 ;
        this.pageRequest.pageSize = 10;
        this.$refs.JicTable.restPage();
        this.findPage();
      }
    },

    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      var temp = [];
      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
  },
  watch: {
    activeName(val) {
      if(val != '0'){
        this.filters.status = val;
      }else{
        this.filters.status = null;
      }
      this.findPage();
    }

  },
  created() {
    // init the default selected tab
    const tab = this.$route.query.tab
    if (tab) {
      this.activeName = tab
    }
  },
  mounted() {
    this.initColumns();
  }
};
</script>

<style scoped lang="scss">
  .reset {
    background-color: #fff;
    color: #409eff;
  }

/deep/ .el-tabs--card>.el-tabs__header .el-tabs__item:first-child{
  border-left: 1px solid #9B9DA3 !important;
  &.is-active {
    border-color: #0090FF !important;
  }
}
.search-input{
  .times{
    .w211{
      width: 211px !important;
      /deep/ .el-input__inner{
        width: 211px !important;
      }
    }
  }
}
</style>
